package com.jie.jie.rili;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import com.jaydenxiao.common.commonutils.LogUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


/**
 * Created by Administrator on 2017/3/1.
 */

public class RiliView extends View {

    private String TAG = "rili";
    private Date selectedStartDate;
    private Date selectedEndDate;
    private Date curDate; // 当前日历显示的月
    private Date today; // 今天的日期文字显示红色
    private Date downDate; // 手指按下状态时临时日期
    private Date showFirstDate, showLastDate; // 日历显示的第一个日期和最后一个日期
    private int downIndex; // 按下的格子索引
    private Calendar calendar;
    private RiliView.Surface surface;
    private int[] date = new int[42]; // 日历显示数字
    private int curStartIndex, curEndIndex; // 当前显示的日历起始的索引
    private ArrayList<Long> returntime;
    private ArrayList<Long> allReturnTime;

    public void setReturntime(ArrayList<Long> returntime) {
        this.returntime = returntime;
    }

    public void setAllReturnTime(List<Long> allReturnTime) {
        this.allReturnTime = (ArrayList<Long>) allReturnTime;
    }

    public RiliView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public RiliView(Context context) {
        super(context);
        init();
    }
    private void init() {
        curDate = selectedStartDate = selectedEndDate = today = new Date();
        calendar = Calendar.getInstance();
        calendar.setTime(curDate);
        surface = new Surface();
        surface.density = getResources().getDisplayMetrics().density;
        setBackgroundColor(surface.bgColor);
//        setOnTouchListener(this);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        surface.allHeight = getResources().getDisplayMetrics().heightPixels*2/5;
        surface.allWidth = getResources().getDisplayMetrics().widthPixels;
        widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(surface.allWidth,
                View.MeasureSpec.EXACTLY);
        heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(surface.allHeight,
                View.MeasureSpec.EXACTLY);
        setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
    @Override
    protected void onLayout(boolean changed, int left, int top, int right,
                            int bottom) {
        LogUtils.logd(TAG, "[onLayout] changed:"
                + (changed ? "new size" : "not change") + " left:" + left
                + " top:" + top + " right:" + right + " bottom:" + bottom);
        if (changed) {
            surface.init();
        }
        super.onLayout(changed, left, top, right, bottom);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawRoundRect(0,0,surface.allWidth,surface.allHeight/7,40,40,surface.weekBgPaint);
        float weekTextY = surface.weekHeight * 3 / 4f;
        for (int i = 0; i < surface.weekText.length; i++) {
            float weekTextX = i
                    * surface.cellWidth
                    + (surface.cellWidth - surface.weekPaint
                    .measureText(surface.weekText[i])) / 2f;
            canvas.drawText(surface.weekText[i], weekTextX, weekTextY,
                    surface.weekPaint);
        }

        // 计算日期
        calculateDate();
        // today index
        int todayIndex = -1;
        calendar.setTime(curDate);
        String curYearAndMonth = calendar.get(Calendar.YEAR) + ""
                + calendar.get(Calendar.MONTH);
        calendar.setTime(today);
        String todayYearAndMonth = calendar.get(Calendar.YEAR) + ""
                + calendar.get(Calendar.MONTH);
        if (curYearAndMonth.equals(todayYearAndMonth)) {
            int todayNumber = calendar.get(Calendar.DAY_OF_MONTH);
            todayIndex = curStartIndex + todayNumber - 1;
        }
        for (int i = 0; i < 42; i++) {
            int color = surface.textColor;
            if (isLastMonth(i)) {
                color = surface.borderColor;
            } else if (isNextMonth(i)) {
                color = surface.borderColor;
            }
            if (todayIndex != -1 && i == todayIndex) {
                color = surface.todayNumberColor;
            }
            drawCellText(canvas, i, date[i] + "", color);
        }
        ArrayList<Long> returnTime = getReturnTime();
//        ArrayList<Long> returnTime = (ArrayList<Long>) returntime;
        LogUtils.loge(String.valueOf(returnTime.size()));
        if (returnTime.size() != 0) {
            for (long time : returnTime) {
                Date date = new Date(time);
                Calendar calendar1 = Calendar.getInstance();
                calendar1.setTime(date);
                int i = calendar1.get(Calendar.DAY_OF_MONTH);
                LogUtils.loge(time+"   "+String.valueOf(i));
                LogUtils.loge(time+"   "+String.valueOf(curStartIndex));
                i = i + curStartIndex - 1;
                drawCirle(canvas, i);

            }
        }
        super.onDraw(canvas);

    }


    //画外圆
    private void drawCirle(Canvas canvas, int index) {
        int x = getXByIndex(index);
        int y = getYByIndex(index);
        float cellY = surface.weekHeight + (y - 1)
                * surface.cellHeight + surface.cellHeight * 2 / 3.3f;
        float cellX = (surface.cellWidth * (x - 1))
                + (surface.cellWidth )
                / 1.9f;
        canvas.drawCircle(cellX,cellY,surface.cellHeight*3/8,surface.returnPaint);
    }
    /**
     *
     * @param canvas
     * @param index
     * @param text
     */
    private void drawCellText(Canvas canvas, int index, String text, int color) {
        int x = getXByIndex(index);
        int y = getYByIndex(index);
        surface.datePaint.setColor(color);
        float cellY = surface.weekHeight + (y - 1)
                * surface.cellHeight + surface.cellHeight * 3 / 4f;
        float cellX = (surface.cellWidth * (x - 1))
                + (surface.cellWidth - surface.datePaint.measureText(text))
                / 2f;
        canvas.drawText(text, cellX, cellY, surface.datePaint);
    }


    // 获得当前应该显示的年月
    public String getYearAndmonth() {
        calendar.setTime(curDate);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        return year + "年" + surface.monthText[month]+"月";
    }
    private ArrayList<Long> getReturnTime() {
        returntime = new ArrayList<>();
        if (allReturnTime == null) {
            LogUtils.loge("ssssssssss");
            return null;
        }
        for (long time : allReturnTime) {
            LogUtils.loge("aaaaa");
            if (isHasDay(time)) {
                returntime.add(time);
                LogUtils.loge(String.valueOf(returntime.size()));
            }
        }
        return (ArrayList<Long>) returntime;
    }

    public boolean isHasDay(long time) {
        Calendar calendar1 = Calendar.getInstance();
        Date date = new Date(time);
        calendar1.setTime(date);
        int month = calendar1.get(Calendar.MONTH);
        String s = calendar1.get(Calendar.YEAR) + "年" + surface.monthText[month]+"月";;
        return s.equals(getYearAndmonth());
    }

    //上一月
    public String clickLeftMonth(){
        calendar.setTime(curDate);
        calendar.add(Calendar.MONTH, -1);
        curDate = calendar.getTime();
        invalidate();
        return getYearAndmonth();
    }
    //下一月
    public String clickRightMonth(){
        calendar.setTime(curDate);
        calendar.add(Calendar.MONTH, 1);
        curDate = calendar.getTime();
        invalidate();
        return getYearAndmonth();
    }


    private int getXByIndex(int i) {
        return i % 7 + 1; // 1 2 3 4 5 6 7
    }


    private int getYByIndex(int i) {
        return i / 7 + 1; // 1 2 3 4 5 6
    }

    private boolean isLastMonth(int i) {
        if (i < curStartIndex) {
            return true;
        }
        return false;
    }

    private boolean isNextMonth(int i) {
        if (i >= curEndIndex) {
            return true;
        }
        return false;
    }

    private void calculateDate() {
        calendar.setTime(curDate);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        int dayInWeek = calendar.get(Calendar.DAY_OF_WEEK);
        LogUtils.logd(TAG, "day in week:" + dayInWeek);
        int monthStart = dayInWeek;
        if (monthStart == 1) {
            monthStart = 8;
        }
        monthStart -= 1;  //以日为开头-1，以星期一为开头-2
        curStartIndex = monthStart;
        date[monthStart] = 1;
        // last month
        if (monthStart > 0) {
            calendar.set(Calendar.DAY_OF_MONTH, 0);
            int dayInmonth = calendar.get(Calendar.DAY_OF_MONTH);
            for (int i = monthStart - 1; i >= 0; i--) {
                date[i] = dayInmonth;
                dayInmonth--;
            }
            calendar.set(Calendar.DAY_OF_MONTH, date[0]);
        }
        showFirstDate = calendar.getTime();
        // this month
        calendar.setTime(curDate);
        calendar.add(Calendar.MONTH, 1);
        calendar.set(Calendar.DAY_OF_MONTH, 0);
        // Log.d(TAG, "m:" + calendar.get(Calendar.MONTH) + " d:" +
        // calendar.get(Calendar.DAY_OF_MONTH));
        int monthDay = calendar.get(Calendar.DAY_OF_MONTH);
        for (int i = 1; i < monthDay; i++) {
            date[monthStart + i] = i + 1;
        }
        curEndIndex = monthStart + monthDay;
        // next month
        for (int i = monthStart + monthDay; i < 42; i++) {
            date[i] = i - (monthStart + monthDay) + 1;
        }
        if (curEndIndex < 42) {
            // 显示了下一月的
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }
        calendar.set(Calendar.DAY_OF_MONTH, date[41]);
        showLastDate = calendar.getTime();
    }

    public class Surface {
        public float density;
        public int allWidth;
        public int allHeight;
        public float weekHeight; // 显示星期的高度
        public float cellWidth; // 日期方框宽度
        public float cellHeight; // 日期方框高度
        public int bgColor = Color.parseColor("#FFFFFF");
        private int textColor = Color.BLACK;
        private int borderColor = Color.GRAY;
        public int todayNumberColor = Color.RED;
        public int weekBgColor = Color.parseColor("#ff7700");
        public Paint weekBgPaint;
        public Paint weekPaint;
        public Paint datePaint;
        //        public Path boxPath; // 边框路径
        public String[] weekText = {"日", "一", "二", "三", "四", "五", "六"};
        public String[] monthText = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"};
        public Paint returnPaint;
        public void init() {
            float temp = allHeight / 7f;
//            monthHeight = 0;//(float) ((temp + temp * 0.3f) * 0.6);
            //monthChangeWidth = monthHeight * 1.5f;
            weekHeight = (float) ((temp + temp * 0.3f) * 0.7);
            cellHeight = (allHeight  - weekHeight) / 6f;
            cellWidth = allWidth / 7f;
            float textSize = cellHeight * 0.4f;
            Log.d(TAG, "text size:" + textSize);
            weekPaint = new Paint();
            weekPaint.setColor(textColor);
            weekPaint.setAntiAlias(true);
            float weekTextSize = weekHeight * 0.6f;
            weekPaint.setTextSize(weekTextSize);
            weekPaint.setTypeface(Typeface.DEFAULT_BOLD);
            weekBgPaint = new Paint();
            weekBgPaint.setAntiAlias(true);
            weekBgPaint.setColor(weekBgColor);
            weekBgPaint.setStyle(Paint.Style.FILL);
            datePaint = new Paint();
            datePaint.setColor(textColor);
            datePaint.setAntiAlias(true);
            float cellTextSize = cellHeight * 0.5f;
            datePaint.setTextSize(cellTextSize);
            datePaint.setTypeface(Typeface.DEFAULT_BOLD);

            returnPaint = new Paint();
            returnPaint.setAntiAlias(true);
            returnPaint.setColor(todayNumberColor);
            returnPaint.setStyle(Paint.Style.STROKE);

        }


    }
}
